//
//  LTMessageViewController.m
//  LTChat
//
//  Created by apple on 4/21/14.
//  Copyright (c) 2014 fantasy. All rights reserved.
//

#import "LTMessageViewController.h"
#import "AppDelegate.h"
#import "ChatMessage.h"
#import "MessageTableViewCell.h"
#import "Storage.h"

@interface LTMessageViewController ()
<
    UITableViewDataSource,
    UITableViewDelegate,
    XMPPStreamDelegate
>
{
    NSMutableArray *messages;
}
@end

@implementation LTMessageViewController

-(void)dealloc
{
    [[self xmppStream] removeDelegate:self];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        messages = [[NSMutableArray alloc] init];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillChangeFrameNotification object:nil];
    [messages removeAllObjects];
    [messages addObjectsFromArray:[self loadUnReadMessages]];
    [[self xmppStream] addDelegate:self delegateQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)];
    self.title = self.roster.user;
}

-(NSArray *)loadUnReadMessages {
    return [NSArray array];
}

- (void)keyboardWillShow:(NSNotification *)notif {
    
    NSDictionary *userInfo = [notif userInfo];
    
    NSValue* beginValue = [userInfo objectForKey:UIKeyboardFrameBeginUserInfoKey];
    CGRect beginRect = [beginValue CGRectValue];
    
    NSValue* endValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect endRect = [endValue CGRectValue];
    CGRect table_frame = self.view.bounds;
    
    if ((endRect.origin.x - beginRect.origin.x) >= 320.0 || (endRect.origin.y - beginRect.origin.y) >= 100.0) {
    } else {
        table_frame.size.height = table_frame.size.height - endRect.size.height;
    }
    
    [self.contentView setFrame:table_frame];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(IBAction)sendMessage:(id)sender
{
    //NSString *message = self.messageTextField.text;
    NSString *message = self.messageTextField.text;
    if ([message length] <= 0) {
        return;
    }
    XMPPStream *stream = [self xmppStream];
    //XMPPFramework主要是通过KissXML来生成XML文件
    //生成<body>文档
    NSXMLElement *body = [NSXMLElement elementWithName:@"body"];
    [body setStringValue:message];
    
    XMPPMessage *mes = [XMPPMessage messageWithType:@"chat" to:_roster.jid];
    [mes addAttributeWithName:@"from" stringValue:[[stream myJID] description]];
    //
    NSTimeInterval tim = (long)([[NSDate date] timeIntervalSince1970] * 1000);
    [mes addAttributeWithName:@"createDt" integerValue:tim];
    
    //组合
    [mes addChild:body];
    //发送消息
    [stream sendElement:mes];
    self.messageTextField.text = nil;
    ChatMessage *chatMsg = [[ChatMessage alloc] initWithElement:mes];
    [messages addObject:chatMsg];
    [[Storage shareStance] saveMessageToDB:chatMsg];
    [[self tableView] reloadData];
    
    NSInteger s = [self.tableView numberOfSections];
    if (s<1) return;
    NSInteger r = [self.tableView numberOfRowsInSection:s-1];
    if (r<1) return;
    
    NSIndexPath *ip = [NSIndexPath indexPathForRow:r-1 inSection:s-1];
    
    [self.tableView scrollToRowAtIndexPath:ip atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    
}

-(AppDelegate *)appDelegate{
    
    return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}

-(XMPPStream *)xmppStream{
    
    return [[[self appDelegate] xmppChatManager] xmppStream];
}

-(void)processMessage:(XMPPMessage *)message
{
    ChatMessage *msg = [[ChatMessage alloc] initWithElement:message];
    [messages addObject:msg];
    [[self tableView] reloadData];
}

-(void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message
{
    NSLog(@"%@",message);
    [self performSelectorOnMainThread:@selector(processMessage:) withObject:message waitUntilDone:NO];
}

//消息发送状态检测
- (void)xmppStream:(XMPPStream *)sender didSendMessage:(XMPPMessage *)message
{
    NSLog(@"didSendMessage:%@",message.description);
}

-(void)xmppStream:(XMPPStream *)sender didFailToSendMessage:(XMPPMessage *)message error:(NSError *)error
{
    NSLog(@"didFailToSendMessage:%@",error.description);
}

-(void)xmppStream:(XMPPStream *)sender didReceiveError:(DDXMLElement *)error
{
    NSLog(@"%s --> %@",__FUNCTION__,error);
}

-(void)xmppStream:(XMPPStream *)sender didReceivePresence:(XMPPPresence *)presence
{
    NSLog(@"%s --> %@",__FUNCTION__,presence);
}

-(BOOL)hidesBottomBarWhenPushed
{
    return YES;
}

#pragma mark - UItableViewDataSource & UITableViewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [messages count];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentify = @"cellIdentify";
    MessageTableViewCell *cell = (MessageTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentify];
    if (cell == nil) {
        cell = [[MessageTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentify];
    }
    ChatMessage *msg = [messages objectAtIndex:indexPath.row];
    [cell setMessage:msg];
    cell.jid = self.roster.jid;
    cell.myJid = [self xmppStream].myJID;
    return cell;
}

-(void)sendToRoom:(NSString *)roomjid
{
    //NSString *message = self.messageTextField.text;
    NSString *message = self.messageTextField.text;
    if ([message length] <= 0) {
        return;
    }
    XMPPStream *stream = [self xmppStream];
    //XMPPFramework主要是通过KissXML来生成XML文件
    //生成<body>文档
    NSXMLElement *body = [NSXMLElement elementWithName:@"body"];
    [body setStringValue:message];
    
    XMPPMessage *mes = [XMPPMessage messageWithType:@"groupchat" to:[XMPPJID jidWithString:roomjid]];
    [mes addAttributeWithName:@"from" stringValue:[[stream myJID] description]];
    //
    NSTimeInterval tim = (long)([[NSDate date] timeIntervalSince1970] * 1000);
    [mes addAttributeWithName:@"createDt" integerValue:tim];
    
    //组合
    [mes addChild:body];
    //发送消息
    [stream sendElement:mes];
    self.messageTextField.text = nil;
    ChatMessage *chatMsg = [[ChatMessage alloc] initWithElement:mes];
    [messages addObject:chatMsg];
    [[Storage shareStance] saveMessageToDB:chatMsg];
    [[self tableView] reloadData];
    
    NSInteger s = [self.tableView numberOfSections];
    if (s<1) return;
    NSInteger r = [self.tableView numberOfRowsInSection:s-1];
    if (r<1) return;
    
    NSIndexPath *ip = [NSIndexPath indexPathForRow:r-1 inSection:s-1];
    
    [self.tableView scrollToRowAtIndexPath:ip atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}

@end
